# -*- coding: utf-8 -*-
# @Author   : 白云酱
# Data      :
# Software  :PyCharm
# version   :python 3.10
# @File     :banner_script.py

from bs4 import BeautifulSoup

from libs.driver_init import DriverInit
from utils.common_util import Common
from utils.db_util import DBUtil

class BannerScript:
    def __init__(self):
        self.url = "https://m.X7sy.com"
        # 定位一级导航栏的元素
        self.select_expression = "dingbu_nav"
        # 断言页面的元素
        self.exits = ("xpath","._nav")
        # 入数据库xpath
        self.set_xpath = "('xpath','//*[@class = \"dingbu_nav\"]/a[{index}]')"

    def get(self):
        """获取页面元素内容"""
        driver = DriverInit()
        driver.to_browser().get(self.url)
        html = driver.to_browser().get_source()
        # 解析页面
        soup = BeautifulSoup(html, 'html.parser')
        # 获取一级导航栏的数据
        data = soup.find('div',class_ = 'dingdu_nav').find_all('a')
        print(data)
        a_list = []
        for d in data:
            name = d.get_text().strip()
            href = self.url + d['href']
            a_list.append({"name":name,"href":href})
        return len(a_list),a_list

    def run(self):
        number,data_list = self.get()
        range_num = 1
        for n in range(number):
            xpath = self.set_xpath.format(index=range_num)
            time = Common().create_time()
            name = data_list[n].get("name")
            href = data_list[n].get('href')
            desc = "官网首页导航栏元素"
            sql = f"INSERT INTO sy_banner(classification_name,locator,link,create_time"\
                  f"values({repr(name)},{repr(href)},{repr(time)})"
            range_num += 1
            print(sql)
            DBUtil.exe_sql(sql)


if __name__ =='__main__':
    BannerScript().run()